package com.biostime.qdingding.modules.qd.api;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.biostime.qdingding.common.api.FastResponse;
import com.biostime.qdingding.common.api.ListResponse;
import com.biostime.qdingding.common.utils.StringUtils;
import com.biostime.qdingding.common.web.BaseController;
import com.biostime.qdingding.modules.qd.web.UploadController.UpLoad;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
@RequestMapping(value = "${adminPath}/qd/api/upload")
public class UploadApi extends BaseController {
	@SuppressWarnings("rawtypes")
	@ResponseBody()
	@RequestMapping(value = {""},produces="application/json;charset=utf-8")
	public ListResponse<Map> processRequest(HttpServletRequest request, HttpServletResponse response){
		String type = request.getParameter("Type");
		int isWater = StringUtils.toInteger(request.getParameter("IsWater"));
		int isThumbnail =StringUtils.toInteger(request.getParameter("IsThumbnail"));
		int errorCode=0;
		int subCode=0;
		String msg="";
		List<Map> list=new ArrayList<Map>();
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if(!isMultipart){
			errorCode=1;
			subCode=0;
			msg="form标签enctype必须为multipart/form-data！";
		}else if(StringUtils.isEmpty(type)){
			errorCode=1;
			subCode=1;
			msg="请设置上传分类(type参数为空)！";
		}else{
			boolean _iswater = isWater==1; //水印
			boolean _isthumbnail = isThumbnail==1; //缩略图
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload= new ServletFileUpload(factory);
			try{
				@SuppressWarnings("unchecked")
				List<FileItem> items = upload.parseRequest(request) ; // 接收全部内容
				if(items.size()<=0){
					errorCode=1;
					subCode=1;
					msg = "请选择要上传文件！";
				}else{
					UpLoad upFiles = new UpLoad();
					ObjectMapper mapper = new ObjectMapper();
					for(FileItem item : items){
						if(item.getFieldName().startsWith("Filedata")){
							 String res = upFiles.fileSaveAs(type, item, _isthumbnail, _iswater);
							 Map map=mapper.readValue(res, Map.class);
							 list.add(map);
						}
					}
					msg="上传成功";
				}
			}catch(Exception e){
				errorCode=1;
				subCode=0;
				msg="系统错误，上传失败";
			}
		}
		return FastResponse.create().errCode(errorCode).subCode(subCode).errMsg(msg).list(list);
	}
}
